<template>
  <el-cascader :options="organizationCascaderOptions" :props="{ checkStrictly: true }" :filterable="true"
    :placeholder="placeholder" />
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import type { OrganizationDto } from '@/utils/api/organization/type';
import { getSelectAsync } from '@/utils/api/organization';
import { propTypes } from '@/utils/propTypes';

const props = defineProps({
  placeholder: propTypes.string.def('请选择上级组织'),
  keyType: propTypes.number.def(0)
});

/* 组织级联表 */
interface CascaderOption {
  value: string;
  label: string;
  code: string;
  children?: CascaderOption[];
}
const organizationCascaderOptions = ref<CascaderOption[]>([]);
// 组织OrganizationSelect转化成Tree数组
const convertSelectOrganization = (
  data: Array<OrganizationDto>,
  parentId?: string | null
): Array<CascaderOption> => {
  let arrays = new Array<CascaderOption>();
  let dataList = data
    .filter((it) => it.parentId === parentId)
    .sort(
      (a, b) =>
        parseInt(a.code.split('.')[a.code.split('.').length - 1]) -
        parseInt(b.code.split('.')[b.code.split('.').length - 1])
    );
  dataList.forEach((item) => {
    let tree: CascaderOption = {
      label: item.displayName,
      value: props.keyType === 0? item.id : item.code,
      code: item.code,
      children: convertSelectOrganization(data, item.id)
    };
    arrays.push(tree);
  });
  return arrays;
};
// 初始化组织下拉
const initOrganizationSelectAsync = async () => {
  organizationCascaderOptions.value = convertSelectOrganization(await getSelectAsync(true), null);
};

//组件挂载完毕
onMounted(async () => {
  await initOrganizationSelectAsync();
});
</script>
<style scoped lang="scss"></style>
